import React, { useState, useMemo, useEffect, useRef } from 'react'
import { Shadow } from 'react-native-shadow-2'
import useGetStatusBar from '../utils/useGetStatusBar'
import { flexCol, common } from '../assets/style/common'
import OwlButton from '../component/common/owlButton'
import OwlInputRef, { OwlInputMethod } from '../component/common/owlInput'
import {
  ImageBackground,
  StatusBar,
  StyleSheet,
  Text,
  View,
  Dimensions,
  Pressable,
  ScrollView,
} from 'react-native'
import { SafeAreaView } from 'react-native-safe-area-context'
import { useStore } from '../store'
import { observer } from 'mobx-react-lite'
import OwlLoadingWrap from '../component/common/owlLoadingWrap'

const { width, height } = Dimensions.get('screen')

function Login({ navigation }: any): JSX.Element {
  const [statusBarH] = useGetStatusBar()
  const [check, setCheck] = useState(false)
  const [type, setType] = useState<'code' | 'password' | 'register'>('code')
  const [showPasswordInfo, setPasswordInfo] = useState(false)
  const [loading, setLoading] = useState(false)
  const { userStore } = useStore()
  const phoneRef = useRef<OwlInputMethod>(null)
  const codeRef = useRef<OwlInputMethod>(null)
  const pwdRef = useRef<OwlInputMethod>(null)
  const title = useMemo(() => {
    switch (type) {
      case 'code':
        return '验证码登录'
      case 'password':
        return '密码登录'
      case 'register':
        return '注册'
      default:
        ''
    }
  }, [type])
  async function onLogin() {
    try {
      setLoading(true)
      const ret = await userStore.login({
        type: type,
        code: codeRef.current ? codeRef.current.getValue() : '',
        phone: phoneRef.current ? phoneRef.current.getValue() : '',
        password: pwdRef.current ? pwdRef.current.getValue() : '',
      })
      setLoading(false)
      if (ret) {
        navigation.navigate('Model', { type: 'info', message: ret })
      } else {
        navigation.navigate('Model', {
          type: 'info',
          message: '登录成功',
          onClose: () => {
            goHome()
          },
        })
      }
    } catch (e) {
      console.log('error', e)
    }
  }
  function switchType() {
    setType(val => (val === 'code' ? 'password' : 'code'))
  }
  function switchLogin() {
    setType(val => (val === 'register' ? 'code' : 'register'))
  }
  function goHome() {
    clearInput()
    navigation.navigate('Home')
  }
  function clearInput() {
    phoneRef.current?.setValue('')
    codeRef.current?.setValue('')
    pwdRef.current?.setValue('')
  }
  return (
    <ScrollView
      keyboardShouldPersistTaps="handled"
      scrollEnabled={false}
      keyboardDismissMode="on-drag"
    >
      <StatusBar
        translucent
        backgroundColor="rgba(0,0,0,0)"
        barStyle={'light-content'}
      />
      <ImageBackground
        source={require('../assets/images/login-bgm.png')}
        imageStyle={{
          resizeMode: 'cover',
          width: width,
          height: height,
        }}
        style={styles.bgm}
      >
        <View
          style={StyleSheet.compose(styles.headerMenu, {
            marginTop: statusBarH + 12,
          })}
        >
          <Shadow startColor="#00000008" distance={4} offset={[0, 2]}>
            <Pressable onPress={goHome} style={styles.menuWrap}>
              <Text style={styles.topMenu}>&#xe63e;</Text>
            </Pressable>
          </Shadow>
        </View>
        <View style={styles.body}>
          <View>
            <Text style={styles.mainTitle}>{title}</Text>
          </View>
          {type !== 'register' && (
            <View
              style={{
                display: 'flex',
                justifyContent: 'flex-end',
                width: '100%',
                flexDirection: 'row',
                marginBottom: 24,
              }}
            >
              <Text style={styles.switchType} onPress={switchType}>
                {type === 'code' ? '密码登录' : '验证码登录'}
              </Text>
            </View>
          )}
          <OwlInputRef
            keyboardType="numeric"
            ref={phoneRef}
            placeholder="手机号码"
          >
            <Text style={styles.textIcon}>&#xe696;</Text>
          </OwlInputRef>
          {(type === 'code' || type === 'register') && (
            <OwlInputRef
              keyboardType="numeric"
              ref={codeRef}
              placeholder="输入验证码"
              inputStyle={{ paddingRight: 2 }}
            >
              <SendCodeButton />
            </OwlInputRef>
          )}
          {(type === 'register' || type === 'password') && (
            <OwlInputRef
              ref={pwdRef}
              placeholder="密码"
              password={!showPasswordInfo}
              returnKeyLabel="确认"
              returnKeyType="done"
            >
              <Pressable onPress={() => setPasswordInfo(val => !val)}>
                {showPasswordInfo ? (
                  <Text style={styles.textIcon}>&#xe658;</Text>
                ) : (
                  <Text style={styles.textIcon}>&#xe6fa;</Text>
                )}
              </Pressable>
            </OwlInputRef>
          )}
          <View style={flexCol({ marginBottom: 48 })}>
            <Pressable
              onPress={() => setCheck(val => !val)}
              style={flexCol.default}
            >
              <View style={styles.checkBox}>
                <Text style={[styles.checkIcon, { opacity: check ? 1 : 0 }]}>
                  &#xe645;
                </Text>
              </View>
              <Text style={{ color: '#fff', fontSize: 14 }}>
                阅读并接收隐私政策 和 协议
              </Text>
            </Pressable>
            <Text style={styles.switchLogin} onPress={switchLogin}>
              {type === 'register' ? '去登录' : '去注册'}
            </Text>
          </View>
          {type === 'register' ? (
            <OwlLoadingWrap
              coverStyle={{ borderRadius: 8, height: 44 }}
              loading={loading}
            >
              <OwlButton
                linearGradientColors={['#fed66f', '#fbce6a']}
                text="注册"
                textColor="#fff"
                imageSource={require('../assets/icon/registered.png')}
              />
            </OwlLoadingWrap>
          ) : (
            <OwlLoadingWrap
              coverStyle={{ borderRadius: 8, height: 44 }}
              loading={loading}
            >
              <OwlButton
                linearGradientColors={['#57aef0', '#73d7f7']}
                text="登录"
                textColor="#fff"
                onClick={onLogin}
                imageSource={require('../assets/icon/log-in.png')}
                style={{ marginBottom: 24, width: '100%' }}
              />
            </OwlLoadingWrap>
          )}
        </View>
        <SafeAreaView style={styles.bottom}>
          <Text style={styles.otherTit}>其他登录方式</Text>
          <View style={[flexCol.default, { justifyContent: 'space-evenly' }]}>
            <View style={[flexCol.default, { flexDirection: 'column' }]}>
              <Text style={styles.otherIcon}>&#xe7ff;</Text>
              <Text style={styles.otherTxt}>Facebook</Text>
            </View>
            <View style={styles.spliceLine} />
            <View style={[flexCol.default, { flexDirection: 'column' }]}>
              <Text style={styles.otherIcon}>&#xe634;</Text>
              <Text style={styles.otherTxt}>Wechat</Text>
            </View>
          </View>
        </SafeAreaView>
      </ImageBackground>
    </ScrollView>
  )
}

function SendCodeButton() {
  const [time, setTime] = useState(0)
  function onSend() {
    time === 0 && setTime(60)
  }
  useEffect(() => {
    let timeout: any
    if (time > 0) {
      timeout = setTimeout(() => {
        setTime(time - 1)
      }, 1000)
    }
    return () => {
      timeout && clearTimeout(timeout)
    }
  }, [time])
  const text = useMemo(
    () =>
      time === 0 ? '发送验证码' : (time < 10 ? '0' + time : time) + 's后发送',
    [time],
  )
  return (
    <OwlButton
      style={{
        width: 98,
        height: 36,
        borderRadius: 6,
        borderTopRightRadius: 12,
      }}
      linearGradientColors={
        time === 0 ? ['#73d7f7', '#73d7f7'] : ['#ddd', '#e1e1e1']
      }
      textColor="#fff"
      textStyle={sendCodeStyles.textStyle}
      isShadow={false}
      text={text}
      onClick={onSend}
    />
  )
}

const sendCodeStyles = StyleSheet.create({
  textStyle: { fontSize: 14, marginLeft: 0, fontWeight: 400 },
})
const styles = StyleSheet.create({
  headerMenu: {
    display: 'flex',
    justifyContent: 'space-between',
    flexDirection: 'row',
    width: '100%',
    marginTop: 40,
    paddingHorizontal: 12,
  },
  menuWrap: {
    width: 32,
    height: 32,
    backgroundColor: 'rgba(255,255,255,.2)',
    borderRadius: 16,
    borderWidth: 1,
    borderColor: 'rgb(255,255,255)',
    justifyContent: 'center',
    ...common.flexCol,
  },

  topMenu: {
    fontSize: 20,
    color: '#fff',
    fontFamily: 'iconfont',
  },
  body: {
    paddingTop: 104,
    width: '100%',
    paddingHorizontal: 24,
  },
  mainTitle: {
    textAlign: 'center',
    fontSize: 20,
    color: '#fff',
    fontWeight: 'bold',
    paddingBottom: 24,
  },
  switchType: {
    color: '#f1f1f1',
    fontSize: 14,
    textDecorationColor: '#f1f1f1',
    textDecorationLine: 'underline',
  },
  switchLogin: {
    marginLeft: 'auto',
    fontSize: 14,
    textDecorationLine: 'underline',
    textDecorationColor: '#f1f1f1',
    color: '#f1f1f1',
  },
  checkBox: {
    width: 14,
    height: 14,
    borderWidth: 1,
    borderColor: '#fff',
    marginRight: 10,
  },
  checkIcon: {
    fontSize: 12,
    fontFamily: 'iconfont',
    color: '#fff',
  },
  bgm: {
    width: width,
    height: height,
    position: 'relative',
  },
  bottom: {
    width: '100%',
    position: 'absolute',
    bottom: 40,
    height: 120,
  },
  otherTit: {
    textAlign: 'center',
    color: '#ffffff',
    fontSize: 14,
    fontWeight: 'bold',
    marginBottom: 24,
  },
  otherIcon: {
    fontSize: 32,
    marginBottom: 4,
    fontFamily: 'iconfont',
    color: '#ffffff',
  },
  otherTxt: {
    fontSize: 14,
    textAlign: 'center',
    color: '#fff',
  },
  spliceLine: {
    borderLeftColor: '#ffffff99',
    borderLeftWidth: 1,
    height: 24,
  },
  textIcon: {
    fontFamily: 'iconfont',
    fontSize: 20,
    color: '#fff',
  },
})

export default observer(Login)
